//
//  SuffererViewController.m
//  SKinDiary
//
//  Created by pcyang on 16/6/28.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDPaientViewController.h"
#import "SDPaientEditorViewController.h"
#import "SDPaientInfoMgr.h"
#import "SDPaientInfoItem.h"
#import "SDPaientItemCell.h"
#import "SDPaientListData.h"

@interface SDPaientViewController()<UISearchControllerDelegate,UISearchResultsUpdating,SDTableViewDelegate, UITableViewDataSource>
@property(nonatomic,strong)NSArray* mFilteredArray;
@property(nonatomic,strong)UISearchController* mSearchDisplayController;
@property (nonatomic,strong)SDPaientListData* paientListData;
@end

@implementation SDPaientViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initSubviews];
    [self initData];
    [self finishLoading];
    
    
    SDPaientInfoMgr* suffererInfoMgr = [SDPaientInfoMgr shareAGDatabaseManager];
    [suffererInfoMgr creatTable:[SDPaientInfoItem class] tableName:kPaientTableName keyName:nil primaryKey:nil];
    
    SDPaientInfoItem* userItem = [[SDPaientInfoItem alloc] init];
    userItem.sId = 100004;
    userItem.name = @"lize";
    
    //  [suffererInfoMgr insert:userItem tableName:kSuffererTableName];
    // [self loadData];
}

-(void)initData
{
    _paientListData = [[SDPaientListData alloc] init];
    [_paientListData reloadDataWithCache:NO];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tableView.editing = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self loadData];
}

-(void)initSubviews
{
    BOOL naviHidden = [self navigationBarHidden];
    if (!naviHidden && self.navBar != nil)
    {
        [self.navBar setTitle:@"新患者数据"];
        UIImage* addImg = LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle, @"actionbar_btn_add.png");
        [self.navBar customNaviLeftButton:self action:@selector(onCreateNewPaient:) image:addImg];
        [self.navBar customNaviRightButton:self action:@selector(onDelete:) title:@"编辑"];
    }
    
    
    [self.tableView removeRefreshHeaderView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.notShowLoadingMore = YES;
    self.tableView.sectionIndexColor = [@"0000aa" toUIColor];
    self.tableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    
    self.mSearchDisplayController = [[UISearchController alloc]initWithSearchResultsController:nil];
    self.mSearchDisplayController.searchBar.frame = CGRectMake(0, 0, 0, 44);
    
    //搜索栏表头视图
    self.tableView.tableHeaderView = self.mSearchDisplayController.searchBar;
    [self.mSearchDisplayController.searchBar sizeToFit];
    self.mSearchDisplayController.searchBar.placeholder = @"搜索";
    
    self.definesPresentationContext = YES;
    self.mSearchDisplayController.hidesNavigationBarDuringPresentation = false;
    self.mSearchDisplayController.dimsBackgroundDuringPresentation = false;
    
    //背景颜色
    self.navigationController.navigationBar.backgroundColor = RGB(0x24, 0xd9, 0xc6);
    self.mSearchDisplayController.searchBar.backgroundColor = RGB(0x24, 0xd9, 0xc6);
    [self.mSearchDisplayController.searchBar setBackgroundImage:[UIImage new]];
    self.mSearchDisplayController.searchResultsUpdater = self;
    self.mSearchDisplayController.delegate = self;
    
    for(UIView* view in [[[self.mSearchDisplayController.searchBar subviews]lastObject]subviews] ) {
        
        if([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            [view removeFromSuperview];
        }
        if([view isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            UIButton*cancelButton = [self.mSearchDisplayController.searchBar valueForKey:@"_cancelButton"];
            if (cancelButton != NULL) {
                [cancelButton setTitle:@"取消"forState:UIControlStateNormal];
            }
        }
    }
}

-(void)loadData
{
    SDPaientInfoMgr* suffererInfoMgr = [SDPaientInfoMgr shareAGDatabaseManager];
    NSArray* userList = [suffererInfoMgr selectALL:[SDPaientInfoItem class] tableName:kPaientTableName];
    NSDictionary* indexToFriendsMap = [SDPaientViewController processFriendList:userList];
    NSMutableArray* indexList = nil;
    
    if(indexToFriendsMap.count > 0)
    {
        indexList = [NSMutableArray arrayWithArray:[indexToFriendsMap allKeys]];
        
        [indexList sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
         {
             NSString* one = (NSString*)obj1;
             NSString* two = (NSString*)obj2;
             
             if([one isEqualToString:@"#"])
                 return NSOrderedDescending;
             else if([two isEqualToString:@"#"])
                 return NSOrderedAscending;
             
             return [one compare:two];
         }];
    }
    _indexToFriendList = indexToFriendsMap;
    _indexList = indexList;
    
    [self.tableView reloadData];
}

- (BOOL)navigationBarHidden
{
    return NO;
}

- (BOOL)isDataEmpty
{
    return NO;
}

+(NSDictionary*) processFriendList:(NSArray*) userList
{
    NSMutableDictionary* indexToFriendsMap = nil;
    if(userList.count > 0)
    {
        indexToFriendsMap = [NSMutableDictionary dictionaryWithCapacity:24];
        for(SDPaientInfoItem* person in userList)
        {
            NSString* name = person.name;
            if(name.length > 0)
            {
                name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                CFMutableStringRef str = CFStringCreateMutableCopy(NULL, 0, (__bridge CFStringRef)(name));
                CFStringTransform(str, NULL, kCFStringTransformMandarinLatin, NO);
                CFStringTransform(str, NULL, kCFStringTransformStripDiacritics, NO);
                
                NSString* pinYing = (__bridge NSString*)str;
                if(pinYing.length > 0)
                {
                    unichar c = [pinYing characterAtIndex:0];
                    if(c>='a' && c<='z')
                        c -= ('a'-'A');
                    
                    if(c>='A' && c<='Z')
                    {
                        NSString* index = [NSString stringWithFormat:@"%c", c];
                        NSMutableArray* tmpArr = [indexToFriendsMap objectForKey:index];
                        
                        if(nil == tmpArr)
                        {
                            tmpArr = [NSMutableArray arrayWithCapacity:8];
                            [indexToFriendsMap setObject:tmpArr forKey:index];
                        }
                        person.pingY = pinYing;
                        [tmpArr addObject:person];
                    }
                }
                
                CFRelease(str);
            }
        }
    }
    
    return indexToFriendsMap;
}

-(NSArray*) searchResultsByName:(NSString*)name
{
    NSArray* results  = nil;
    if(name.length > 0)
    {
        name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        CFMutableStringRef str = CFStringCreateMutableCopy(NULL, 0, (__bridge CFStringRef)(name));
        CFStringTransform(str, NULL, kCFStringTransformMandarinLatin, NO);
        CFStringTransform(str, NULL, kCFStringTransformStripDiacritics, NO);
        
        NSString* pinYing = (__bridge NSString*)str;
        if(pinYing.length > 0)
        {
            unichar c = [pinYing characterAtIndex:0];
            if(c>='a' && c<='z')
                c -= ('a'-'A');
            
            if(c>='A' && c<='Z')
            {
                NSString* index = [NSString stringWithFormat:@"%c", c];
                results = [_indexToFriendList objectForKey:index];
                
            }
        }
        
        CFRelease(str);
    }
    
    return results;
}

#pragma mark - ui event
-(void)onCreateNewPaient:(id)sender
{
    SDPaientEditorViewController* editorViewController = [[SDPaientEditorViewController alloc] init];
    [self presentViewController:editorViewController animated:YES completion:NULL];
}

-(void)onDelete:(id)sender
{
    [self.tableView setEditing:!self.tableView.isEditing animated:YES];
    
}

#pragma mark - SDTableView
- (void)tableViewShouldRefreshData:(SDTableView*)tableView
{
}

- (void)tableViewShouldLoadMoreData:(SDTableView*)tableView
{
}

- (BOOL)tableViewDataIsLoading:(SDTableView*)tableView
{
    return NO;
}

- (BOOL)tableViewHasMoreData:(SDTableView*)tableView
{
    return  NO;
}

- (NSDate*)tableViewDataLastUpdateTime:(SDTableView*)tableView
{
    return nil;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kPaientCellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(0==section)
        return 0.f;
    
    return 20.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(0==section)
        return nil;
    
    section -= 1;
    
    UILabel* lable = [[UILabel alloc] init];
    lable.textAlignment = NSTextAlignmentLeft;
    lable.backgroundColor = [UIColor clearColor];
    lable.textColor = [UIColor blackColor];
    lable.font = [UIFont systemFontOfSize:14.f];
    
    if(_indexList.count > section)
    {
        NSString* index = [_indexList objectAtIndex:section];
        lable.text = index;
    }
    
    UIView* bg = [[UIView alloc] initWithFrame:CGRectZero];
    bg.backgroundColor = RGB(0xf3, 0xf4, 0xf4);
    
    [lable sizeToFit];
    lable.frame = CGRectOffset(lable.frame, 10.f, 0.f);
    [bg addSubview:lable];
    
    return bg;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if (section<_indexList.count)
    {
        NSString* index = [_indexList objectAtIndex:section];
        NSArray* userList = [_indexToFriendList objectForKey:index];
        
        if (userList && userList.count > row)
        {
            SDPaientInfoItem* userItem = [userList objectAtIndex:row];
            
            //            NSString *personid = [NSString stringWithFormat:@"%lld", info.actorId];
            //            VPPersonalViewController* personalCtrler = [[VPPersonalViewController alloc] init];
            //            personalCtrler.avatarUrl = info.faceImageUrl;
            //            personalCtrler.personName = info.actorName;
            //            personalCtrler.personID = personid;
            //            personalCtrler.isOwner = NO;
            //            [self.navigationController pushViewController:personalCtrler animated:YES];
        }
    }
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}


-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return @"删除";
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    NSString* index = [_indexList objectAtIndex:section - 1];
    NSArray* userList = [_indexToFriendList objectForKey:index];
    
    if (userList && userList.count > row)
    {
        SDPaientInfoItem* userItem = [userList objectAtIndex:row];
        bool isSuccess = [[SDPaientInfoMgr shareAGDatabaseManager] deleteTableName:kPaientTableName where:[NSString stringWithFormat:@"sId = %ld",userItem.sId]];
        if (isSuccess) {
            NSString* directory = [SDFile getDirectoryInCacheWithName:kAvatarDirectoryName];
            NSString *filePath = [directory stringByAppendingPathComponent:userItem.avatarFileName];
            if ([SDFile fileExist:filePath]) {
                [SDFile deleteItem:filePath];
            }
            [self loadData];
        }
    }
    
}

#pragma mark ---
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.mSearchDisplayController.active ||
        [self.mFilteredArray count] > 0)
    {
        return 1;
    }
    
    return [_indexList count] + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (self.mSearchDisplayController.active ||
        [self.mFilteredArray count] > 0)
    {
        return [self.mFilteredArray count];
    }
    
    section -= 1;
    if(_indexList && section<_indexList.count)
    {
        NSArray* friendList = [_indexToFriendList  objectForKey:[_indexList objectAtIndex:section]];
        
        if (friendList)
            return (!self.mSearchDisplayController.active) ? friendList.count : self.mFilteredArray.count;
        //return friendList.count;
    }
    
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* s_CellName = @"_friendCell_";
    SDPaientItemCell *curCell = [tableView dequeueReusableCellWithIdentifier:s_CellName];
    if (nil == curCell)
    {
        curCell = [[SDPaientItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s_CellName];
        // curCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    if (self.mSearchDisplayController.active ||
        [self.mFilteredArray count] > 0)
    {
        SDPaientInfoItem* userItem = [self.mFilteredArray objectAtIndex:indexPath.row];
        [curCell setCellData:userItem];
    }
    else
    {   NSInteger section = indexPath.section - 1;
        NSInteger row = indexPath.row;
        if (section < _indexList.count)
        {
            NSString* index = [_indexList objectAtIndex:section];
            NSArray* userList = [_indexToFriendList objectForKey:index];
            if (userList && userList.count > row)
            {
                SDPaientInfoItem* userItem = [userList objectAtIndex:row];
                [curCell setCellData:userItem];
            }
        }
        
    }
    return curCell;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if(tableView.contentSize.height>tableView.height && _indexList.count>0)
    {
        NSMutableArray *tmpArr = [NSMutableArray arrayWithObjects:@" ", nil];
        [tmpArr addObjectsFromArray:_indexList];
        return tmpArr;
    }
    
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index;
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    self.mFilteredArray = nil;
    NSString* searchText = searchController.searchBar.text;
    
    // searchText = @"ya";
    // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.title contains[cd] %@ OR SELF.summary contains[cd] %@", searchText, searchText];
    NSArray* results = [self searchResultsByName:searchText];
    
    NSMutableArray* tempResult = [NSMutableArray arrayWithCapacity:10];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pingY contains[cd] %@", searchText];
    
    //NSPredicate* predicate = [NSPredicate predicateWithFormat: @"name contains[cd] 'er'"];
    for(SDPaientInfoItem* userItem in results){
        if([predicate evaluateWithObject:userItem]){ //判断指定的对象是否满足
            [tempResult addObject:userItem];
        }
    }
    
    if (tempResult != nil && tempResult.count > 0) {
        self.mFilteredArray = [tempResult filteredArrayUsingPredicate:predicate];
    }
    [self.tableView reloadData];
    
    //self.mFilteredArray = [_indexToFriendList filter]
    //    self.mFilteredArray = nil;
    //    //NSPredicate 谓词
    //    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"SELF.title contains[cd] %@ ", searchController.searchBar.text];
    //    self.mFilteredArray = [[self.parseResults filteredArrayUsingPredicate:searchPredicate]mutableCopy];
    
}

// --------------------- UISearchController Delegate Methods ------------------//

//- (void)willPresentSearchController:(UISearchController *)searchController
//{
//   // [self.navigationController setNavigationBarHidden:NO animated:NO];
//    self.navigationController.navigationBar.hidden = YES;
//    self.navBar.hidden = YES;
//}
//
//- (void)didPresentSearchController:(UISearchController *)searchController
//{
//    self.navigationController.navigationBar.hidden = YES;
//
//}
//
//- (void)willDismissSearchController:(UISearchController *)searchController
//{
//    //self.navigationController.navigationBar.hidden = YES;
//    self.navBar.hidden = NO;
//}
//
//- (void)didDismissSearchController:(UISearchController *)searchController{
//    //_filteredItems = _items;
//    //[self.tableView reloadData];
//
// //   self.navigationController.navigationBar.hidden = YES;
//   // self.mSearchDisplayController.hidesNavigationBarDuringPresentation = YES;
//}

@end
